package SGEngine

import (
	"fmt"
	"freetypego"
	"image"
	"image/draw"
	"image/png"
	"os"
)

type FreetypeAtlas struct {
	Width   int
	Height  int
	Pimage  *image.NRGBA
	binPack MaxRectsBinPack
	Tex     *ACTexture
}

func newFreetypeAtlas(_width, _height int) *FreetypeAtlas {
	RFAtlas := new(FreetypeAtlas)
	RFAtlas.Width = _width
	RFAtlas.Height = _height
	RFAtlas.Pimage = image.NewNRGBA(image.Rect(0, 0, _width, _height))
	RFAtlas.binPack.Init(RFAtlas.Width, RFAtlas.Height, false)
	return RFAtlas
}

func (f *FreetypeAtlas) AddCharToAtlas(_fontchar *FreetypeChar) {
	freetypego.Face_Load_Char(int(_fontchar.Mfont.faceIndex), _fontchar.CharCode, 0x4|0x8)
	Face := _fontchar.Mfont.faceIndex
	Face.SaveCurGlyphToCache()
	Face.CacheBBox()
	bbox := freetypego.GetCacheBBox()
	_fontchar.BBox = *bbox
	GlyphSlot := Face.GetGlyphSlot()
	_fontchar.AdvanceX = int(GlyphSlot.Advance.X) / int(64)
	rect := f.binPack.Insert(GlyphSlot.BitMap.Width, GlyphSlot.BitMap.Rows, BinPack_ContactPoint)
	_fontchar.Rect = rect
	if rect.Height == 0 && rect.Width == 0 {
		fmt.Println("error can't add char '" + string(_fontchar.CharCode) + "'")
	}
	f.DrawCharByRect(rect, GlyphSlot.BitMap)

	f.Tex = ACTextureMgr.LoadTextureByNRGBA(f.Pimage, "fff")
}

func (f *FreetypeAtlas) DrawCharByRect(rect PackRect, _fontbmp *freetypego.FT_BitMap) {
	CharImg := _fontbmp.ToNGRBA()
	draw.Draw(f.Pimage, image.Rect(rect.X, rect.Y, rect.X+rect.Width, rect.Y+rect.Height), CharImg, image.ZP, draw.Over)

	file, _ := os.Create("b.png")
	png.Encode(file, f.Pimage)
}
